package com.fan.shop.hibernate.utils;


import java.io.File;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {

	private static String CONFIG_FILE_LOCATION = "hibernate.cfg.xml";
	private static File cfg = new File(CONFIG_FILE_LOCATION);

	private static SessionFactory sessionFactory;
	private static ServiceRegistry serviceRegistry;

	static {

		try {
			
			sessionFactory = configureSessionFactory();

		} catch (Throwable ex) {
			System.err.println("Initial SessionFactory creation failed. " + ex);
		}

	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	private static SessionFactory configureSessionFactory() throws HibernateException {
	    Configuration configuration = new Configuration();
	    configuration.configure(cfg);
	    serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();        
	    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
	    return sessionFactory;
	}

}
